<template>
  <div class="app-container">
    <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets"></i>
      <span>数据列表</span>
      <span style="margin-left: 20px" v-if="list.length && list[0]">{{
        isTanma
          ? formatDate(new Date(nextDate), "yyyy/MM/dd")
          : list.length
          ? formatDate(new Date(list[0].day * 1000), "yyyy/MM/dd")
          : "获取失败"
      }}</span>
      <span style="margin-left: 20px; font-size: 14px; color: #409eff">{{
        fileName
      }}</span>

      <el-button
        size="mini"
        type="primary"
        icon="el-icon-notebook-2"
        class="btn-add"
        @click="openNoteBook"
        style="margin-left: 20px"
        >笔记</el-button
      >

      <el-button
        size="mini"
        type="primary"
        class="btn-add"
        @click="showMatch = true"
        style="margin-left: 20px"
        >获取所有路径</el-button
      >
    </el-card>
    <div class="table-container">
      <!-- 派单审核列表 -->
      <el-table
        ref="productTable"
        :data="list"
        style="width: 100%"
        v-loading="listLoading"
        :default-sort="{ prop: 'userName', order: 'ascending' }"
        border
      >
        <!-- <el-table-column label="编号" align="center">
          <template slot-scope="scope">{{ scope.row.id }}</template>
        </el-table-column> -->
        <el-table-column
          :label="'公司名称（' + (list.length ? list.length : '0') + '）'"
          align="center"
        >
          <template slot-scope="scope">
            <p>{{ scope.row.companyName }}</p>
            <p
              style="color: red"
              v-if="
                scope.row.abandonedPerson != null &&
                0 != scope.row.abandonedPerson.length
              "
            >
              放弃人：{{ scope.row.abandonedPerson }}
            </p>
          </template>
        </el-table-column>
        <el-table-column
          label="时间"
          align="center"
          prop="time"
          sortable
          :filters="[
            { text: '上午', value: 'AM' },
            { text: '下午', value: 'PM' },
          ]"
          :filter-method="filterMethod"
        >
          <template slot-scope="scope">
            <p>{{ scope.row.time }}</p>
          </template>
        </el-table-column>
        <el-table-column label="地址" width="300" align="left">
          <template slot-scope="scope">
            <div style="display: flex; align-items: center">
              <div>{{ scope.row.companyAddress }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="员工" prop="userName" align="center" sortable>
          <template slot-scope="scope">
            <div
              style="
                display: flex;
                align-items: center;
                justify-content: space-between;
              "
            >
              <el-tag
                type="warning"
                style="margin-left: 5px; margin-right: 10px"
                :style="{
                  visibility:
                    scope.row.assignPersonnel === 1 ? 'visible' : 'hidden',
                }"
                >指派</el-tag
              >
              <div>
                {{ scope.row.userName }}
              </div>
              <div></div>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="行程时间"
          align="center"
          prop="duration"
          sortable
        >
          <template slot-scope="scope">
            <div style="display: flex; align-items: center">
              <el-tag
                type="warning"
                style="margin-right: 10px"
                v-if="scope.row.conflictTime === 1"
                >时间冲突</el-tag
              >
              <i
                class="el-icon-truck"
                style="font-size: 18px; margin-left: 20px; margin-right: 10px"
              ></i>
              <div>{{ convertTime(scope.row.duration) }}</div>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="btn-container">
      <el-button type="primary" class="btn" @click="onPass"
        >通过{{ isTanma ? "（探马回传）" : "" }}</el-button
      >
      <el-button
        type="info"
        class="btn"
        style="margin-left: 60px"
        @click="openDialog"
        >修改</el-button
      >
    </div>
    <!-- 数据弹窗 -->
    <div class="dialog-container">
      <!-- 修改数据弹窗 -->
      <el-dialog
        title="修改数据"
        :visible.sync="changeTableVisible"
        top="8vh"
        destroy-on-close
        width="60%"
      >
        <el-table :data="copyList" border :row-class-name="tableRowClassName">
          <el-table-column label="公司名称" align="center">
            <template slot-scope="scope">

              <p v-if="scope.row.join === true"> <el-tag
                    type="warning"
                    style="margin-left: 5px; margin-right: 10px"
                    >已加盟</el-tag
                  ></p>

              <p>{{ scope.row.companyName }}</p>
              <p
                style="color: red"
                v-if="
                  scope.row.abandonedPerson != null &&
                  0 != scope.row.abandonedPerson.length
                "
              >
                放弃人：{{ scope.row.abandonedPerson }}
              </p>
            </template>
          </el-table-column>
          <el-table-column
            label="时间"
            align="center"
            prop="time"
            sortable
            :filters="[
              { text: '上午', value: 'AM' },
              { text: '下午', value: 'PM' },
            ]"
            :filter-method="filterMethod"
          >
            <template slot-scope="scope">
              <p>{{ scope.row.time }}</p>
            </template>
          </el-table-column>
          <el-table-column label="地址" width="240" align="left">
            <template slot-scope="scope">
              <div style="display: flex; align-items: center">
                <div>{{ scope.row.companyAddress }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="员工" width="240" align="center">
            <template slot-scope="scope">
              <div style="display: flex;">
                <div
                  style="
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                  "
                >
                  <el-tag
                    type="warning"
                    style="margin-left: 5px; margin-right: 10px"
                    :style="{
                      visibility:
                        scope.row.assignPersonnel === 1 ? 'visible' : 'hidden',
                    }"
                    >指派</el-tag
                  >
                </div>
                <el-select style="width: 60%;"
                  v-model="scope.row.userId"
                  placeholder="请选择"
                  filterable
                  clearable
                >
                  <el-option
                    v-for="item in scope.row.time.split(':')[0] < 12
                      ? list1
                      : list2"
                    :key="item.id"
                    :label="item.staffName"
                    :value="item.id"
                  >
                    <span style="float: left">{{ item.staffName }}</span>
                    <!-- <span style="float: right; color: #8492a6; font-size: 13px">指派</span> -->
                  </el-option>
                </el-select>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="行程时间" align="center">
            <template slot-scope="scope">
              <div style="display: flex; align-items: center">
                <i
                  class="el-icon-truck"
                  style="font-size: 18px; margin-left: 20px; margin-right: 10px"
                ></i>
                <div>{{ convertTime(scope.row.duration) }}</div>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <span slot="footer" class="dialog-footer">
          <el-button @click="changeTableVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitChangeTable">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 查看匹配数据 -->
      <el-dialog
        title="匹配数据"
        :visible.sync="showMatch"
        top="8vh"
        width="80%"
      >
        <div style="width: 100%">
          <el-tabs type="border-card" v-model="tabsId" width="100%">
            <el-tab-pane label="上午" name="0">
              <all-matching
                :columnList="noonLabel"
                :tableData="noonList"
              ></all-matching>
            </el-tab-pane>
            <el-tab-pane label="下午" name="1">
              <all-matching
                :columnList="afterNoonLabel"
                :tableData="afterNoonList"
              ></all-matching>
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-dialog>
    </div>
    <div>
      <nootbook :visible="visible" @close="close"></nootbook>
    </div>
  </div>
</template>
  <script>
import { formatDate } from "@/utils/date";
import routerDispose from "./routerDispose";
import {
  getGenreateResult,
  approved,
  updateGenreateResult,
  getUpdateGenreateResult,
  callbackInformation,
  allAlgorithmResults,
} from "../../../api/dispatch";
import { filterEmployeess, filterStaffTime } from "../utils/filters";
import { staffListSearch } from "../../../api/staff";
import { checkOrder } from "./utils";
import { mapState } from "vuex";
import allMatching from "./components/allMatching";
const DefaultListQuery = {};
export default {
  name: "audit",
  mixins: [routerDispose],
  components: {
    allMatching,
    nootbook : () => import("./components/notebook")
  },
  data() {
    return {
      formatDate,
      listQuery: Object.assign({}, DefaultListQuery),
      list: [],
      listLoading: false,
      changeTableVisible: false,
      allStaffList: [],
      staffParams: {
        pageNum: 1,
        total: 0,
        pageSize: null,
        lastId: 0,
      },
      list1: [],
      visible: false,
      list2: [],
      copyList: [],
      showMatch: false,
      clientAM: [],
      clientPM: [],
      isSubmit: false,
      allShowMatchList: [],
      nextDate: new Date(),
      fileName: "",
      noonList: [],
      noonLabel: [],
      afterNoonList: [],
      afterNoonLabel: [],
      matchingList: [],
      tabsId: 0,
    };
  },

  created() {
    const { fileName, time } = this.$route.query;
    if (fileName) {
      this.fileName = fileName;
    }
    if (time) {
      this.nextDate = Number(time);
    }
    this.getList();
    window.addEventListener("beforeunload", this.confirmExit);
  },
  beforeDestroy() {
    window.removeEventListener("beforeunload", this.confirmExit);
  },

  watch: {},

  computed: {
    ...mapState(["isTanma"]),
    // 时间换算
    convertTime() {
      return (seconds) => {
        const hours = Math.floor(seconds / 3600);
        const minutes = Math.floor((seconds % 3600) / 60);

        if (hours > 0) {
          return hours + "h " + minutes + "min";
        }

        return minutes + " min";
      };
    },
  },
  methods: {
    /**
     * 获取所有的匹配数据
     * @param {*} param
     */
    getAllAlgorithmResults() {
      allAlgorithmResults().then((res) => {
        console.log(res.data, "匹配数据");
        this.matchingList = res.data;
        this.getAllMatchingList();
      });
    },

    openNoteBook() {
    
      this.visible = true;
      console.log("close", this.visible);;
    },

    close(visible) {
      this.visible = visible;
    },

    tableRowClassName({ row, rowIndex }) {
      let obj = checkOrder(this.copyList);
      let isFalse = obj.includes(rowIndex);
      if (isFalse) {
        return "warning-row";
      }
      return "";
    },

    confirmExit(event) {
      if (!this.isSubmit) {
        // 根据你的业务逻辑判断数据是否被修改
        event.preventDefault();
        event.returnValue = "派单尚未审核通过";
      }
    },

    submitChangeTable() {
      const changeList = this.tableChange(this.list, this.copyList);
      if (!changeList || !changeList.length) {
        this.$message({
          message: "数据未修改",
          type: "error",
        });
        return false;
      }
      // let errList = checkOrder(this.copyList);
      // if (errList && errList.length) {
      //   this.$message({
      //     message: "数据异常，请根据提示修改派单人员！",
      //     type: "error",
      //   });
      //   return false;
      // }

      this.$confirm("是否确定修改?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        updateGenreateResult(changeList).then((res) => {
          this.changeTableVisible = false;
          this.$message({
            type: "success",
            message: "修改成功",
          });
          this.listLoading = true;
          this.getTableChangeResult();
        });
      });
    },

    getTableChangeResult() {
      setTimeout(() => {
        getUpdateGenreateResult().then((res) => {
          this.listLoading = false;
          this.list = res.data.length && res.data.flat().filter(Boolean);
          this.sortList();
        });
      }, 1000);
    },

    tableChange(list1 = [], list2 = []) {
      const modifiedObjects = [];
      for (let i = 0; i < list1.length; i++) {
        const originalObj = list1[i];
        const modifiedObj = list2.find((obj) => obj.id === originalObj.id);

        // 检查对象是否发生了修改
        if (modifiedObj && modifiedObj.userId !== originalObj.userId) {
          modifiedObjects.push({
            id: modifiedObj.id,
            userId: modifiedObj.userId,
          });
        }
      }
      return modifiedObjects;
    },

    openDialog() {
      this.copyList = [];
      this.copyList = JSON.parse(JSON.stringify(this.list));

      console.log("this.copyList", this.copyList);

      this.changeTableVisible = true;
    },

    onPass() {
      this.$confirm("确认审核通过吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        if (this.isTanma) {
          callbackInformation().then((res) => {
            this.isSubmit = true;
            this.$message({
              message: "审核通过成功",
              type: "success",
            }).then((res) => {
              this.$router.replace({
                path: "/dispatch/dispatchHistory",
              });
            });
          });
        } else {
          approved().then((res) => {
            this.isSubmit = true;
            this.$message({
              message: "审核通过成功",
              type: "success",
            }).then((res) => {
              this.$router.replace({
                path: "/dispatch/dispatchHistory",
              });
            });
          });
        }
      });
    },

    filterHandler(value, row) {
      return row.userName === value;
    },
    filterMethod(value, row) {
      let t = row.time.split(":")[0] < 12 ? "AM" : "PM";
      return t === value;
    },

    getList() {
      this.listLoading = true;
      this.getResultList();
    },
    getResultList() {
      getGenreateResult().then((res) => {
        this.listLoading = false;
        this.clientAM = res.data[0];
        this.clientPM = res.data[1];
        this.list = res.data.length && res.data.flat().filter(Boolean);
        this.sortList();
        this.getStaffList();
        this.getAllAlgorithmResults();
      });
    },

    // 获取所有的路径
    getAllMatchingList() {
      try {
        let noonLabel = [];
        let afterNoonLabel = [];
        let noon = [];
        let afterNoon = [];
        this.clientAM.length &&
          this.clientAM.forEach((item) => {
            if (item.assignPersonnel === 1) return;
            noonLabel.push({
              prop: item.id.toString(),
              label: item.companyName,
            });
          });
        this.clientPM.length &&
          this.clientPM.forEach((item) => {
            afterNoonLabel.push({
              prop: item.id.toString(),
              label: item.companyName,
            });
          });
        this.noonLabel = noonLabel;
        this.afterNoonLabel = afterNoonLabel;
        noon = this.getAllResultStaff(this.matchingList.visitNoon, this.list);
        afterNoon = this.getAllResultStaff(
          this.matchingList.visitsAfternoon,
          this.list
        );
        this.noonList = noon;
        this.afterNoonList = afterNoon;
      } catch (error) {
        console.log(error);
      }
    },
    // 获取所有路径人员数据列表
    getAllResultStaff(data = [], list1 = []) {
      let result = [];
      data.length &&
        data.forEach((item) => {
          const exists = result.find((entry) => entry.staffId === item.staffId);
          let selectedResult =
            list1.length &&
            list1.find(
              (i) => i.userId === item.staffId && i.id === item.clientId
            );
          if (exists) {
            exists[item.clientId] = {
              distance: item.distance,
              duration: item.duration,
              selected: selectedResult ? 1 : 0,
            };
          } else {
            const newItem = {
              name: item.staffName,
              staffId: item.staffId,
              status: item.status,
            };

            newItem[item.clientId] = {
              distance: item.distance,
              duration: item.duration,
              selected: selectedResult ? 1 : 0,
            };

            result.push(newItem);
          }
        });
      return result;
    },

    sortList() {
      this.list.length &&
        this.list.sort((a, b) => {
          // 将时间转换为 Date 对象
          const timeA = new Date(`2000/01/01 ${a.time}`);
          const timeB = new Date(`2000/01/01 ${b.time}`);

          return timeA - timeB;
        });
    },
    getStaffList() {
      if (this.staffParams.pageNum === 1) {
        this.allStaffList = [];
        this.staffParams.lastId = 0;
      }
      staffListSearch({
        pageNum: this.staffParams.pageNum,
        lastId: this.staffParams.lastId,
      }).then((res) => {
        this.staffParams.pageSize = res.data.pageSize;
        this.staffParams.total = res.data.total;
        this.staffParams.lastId =
          res.data.data[res.data.data.length - 1].id || 0;
        this.allStaffList = this.allStaffList.concat(res.data.data);
        const totalPage = Math.ceil(res.data.total / res.data.pageSize);
        if (this.staffParams.pageNum < totalPage) {
          this.staffParams.pageNum++;
          this.getStaffList();
        } else {
          setTimeout(() => {
            this.allStaffList = filterEmployeess(
              this.allStaffList,
              this.isTanma ? this.nextDate : this.list[0].day * 1000,
              this.list
            );
            this.list1 = filterStaffTime(
              this.allStaffList,
              "AM",
              this.isTanma ? this.nextDate : this.list[0].day * 1000,
              this.clientAM
            );




            this.list2 = filterStaffTime(
              this.allStaffList,
              "PM",
              this.isTanma ? this.nextDate : this.list[0].day * 1000,
              this.clientPM
            );

            console.log("allStaffList:", this.allStaffList, "clientPM:", this.clientPM, "this.list2", this.list2);

          }, 0);
          this.staffListLoading = false;
        }
      });
    },

    handleSearchList() {
      this.listQuery.pageNum = 1;
      this.getListBySearch();
    },

    getListBySearch() {
      listBySearch(this.listQuery).then((r) => this.getResponse(r));
    },

    handlePublishStatusChange(index, row) {
      let ids = [];
      ids.push(row.id);
      this.updatePublishStatus(row.status, ids);
    },
    handleNewStatusChange(index, row) {
      let ids = [];
      ids.push(row.mid);
      updateHot(row.hot, ids);
    },
  },
};
</script>
  <style>
.table-container {
  display: flex;
  justify-content: space-between;
  flex: auto;
}
.el-table {
  height: max-content !important;
}
.btn-container {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;
  margin-top: 25px;
}
.btn {
  width: 260px;
  height: 40px;
  font-size: 16px;
  letter-spacing: 2px;
}

.el-table .warning-row {
  background: oldlace !important;
  transition: all 0.2s;
}
</style>